<template>
  <div class="register">
    <div class="g-title">
      <span class="left">注册</span>
      <p class="right">已有账号 <span class="go-login" @click="goLogin">去登陆</span></p>
    </div>
    <div class="g-form">
      <el-form :model="registerForm" width="300px" :rules="registerRules" size="small" ref="registerForm">
        <!-- <el-form-item label="账号" prop="account">
          <el-input v-model="registerForm.account" @keyup.native="keyUp" placeholder="请输入账号(不含特殊字符)" onkeyup="value=value.replace(/[^\w\/]/ig,'')"></el-input>
        </el-form-item> -->
        <el-form-item label="名字" prop="name">
          <el-input v-model="registerForm.name" placeholder="请输入名字"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="registerForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="cellphone">
          <el-input v-model="registerForm.cellphone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="14">
            <el-form-item label="验证码" prop="checkCode">
              <el-input v-model="registerForm.checkCode" placeholder="请输入验证码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="btnBox-wrap">
            <div @click="inputCode" :class="['btn', wait ? 'disabledBtn' : '']">{{ codeMessage }}</div>
          </el-col>
        </el-row>
        <el-form-item label="密码" prop="password">
          <el-input show-password v-model="registerForm.password" placeholder="请设置密码包含数字、英文及字符"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input show-password v-model="registerForm.confirmPassword" placeholder="请再次输入密码"></el-input>
        </el-form-item>
        <el-form-item class="my-label" label="标签" prop="tag">
          <el-checkbox-group v-model="registerForm.tag" size="small">
            <el-checkbox @change="changeTag" v-model="item.data_id" :label="item.data_id" :key="item.data_id" v-for="(item, index) in tagList" border>
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <el-checkbox class="argeement" v-model="checked"></el-checkbox>
      <span class="argeement">我已阅读并同意</span>
      <span class="mark">《用户协议》</span>
      <span class="argeement">和</span>
      <span class="mark">《隐私政策》</span>
      <div class="line"></div>
      <el-button class="btn" :loading="loading" @click="handleRegister">
        注册
      </el-button>
    </div>
  </div>
</template>

<script>
import { validEmail, validPhone, isAccout } from '@/utils/validate'
export default {
  scrollToTop: true,
  data() {
    const validateAccount = (rule, value, callback) => {
      if (isAccout(value)) {
        callback()
      } else {
        callback(new Error('账号必须包含字母和数字且以字母开头'))
      }
    }
    const validatorEmail = (rule, value, callback) => {
      if (value === '' || validEmail(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的邮箱格式！'))
      }
    }
    const validateTelPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'))
      }
      if (!validPhone(value)) {
        callback(new Error('您输入的手机号格式不正确'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请确认密码'))
      }
      console.log(value, this.registerForm.password)
      if (value != this.registerForm.password) {
        callback(new Error('两次输入密码不一致，请重新输入'))
        // this.registerForm.confirmPassword = ''
      } else {
        callback()
      }
    }
    return {
      registerForm: {
        // account: '',
        gender: 1,
        name: '',
        email: '',
        cellphone: '',
        tag: [],
        password: '',
        confirmPassword: '',
        checkCode: ''
      },
      checked: true,
      city: ['上海', '北京', '广州', '深圳', '长春', '大连', '杭州', '嘉兴', '昆山', '海宁'],
      registerRules: {
        // account: [
        //   { required: true, message: '账号不能为空', trigger: 'change' },
        //   { validator: validateAccount, trigger: 'change' }
        // ],
        name: [
          { required: true, message: '名字不能为空', trigger: 'change' }
        ],
        gender: [
          { required: true, message: '性别不能为空', trigger: 'change' }
        ],
        email: [
          { required: false, validator: validatorEmail }
        ],
        cellphone: [
          { required: true, message: '手机号不能为空', trigger: 'change' },
          { validator: validateTelPhone, trigger: 'change' }
        ],
        checkCode: [
          { required: true, message: '请输入验证码', trigger: 'change' },
          // { max: 6, min: 6, message: '验证码长度为6', trigger: 'change' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'change' },
          { min: 8, message: '密码长度至少为8位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'change' },
          { validator: validatePassword, trigger: 'change' }
        ]
      },
      codeMessage: '获取验证码',
      wait: false,
      timer: null,
      loading: false,
      option: {
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      },
      tagList: []
    }
  },
  mounted() {
    console.log(this.$route)
    this.getTagList()
  },
  methods: {
    getTagList() {
      this.$api.getTagList({}).then(res => {
        if (res.status == '$SUCCESS') {
          this.tagList = Array.isArray(res.result.item_list) ? res.result.item_list : []
        }
      })
    },
    changeTag() {
      console.log(this.registerForm.tag)
    },
    keyUp(e) {
      e.target.value = e.target.value.replace(/[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,"");
    },
    handleRegister() {
      this.$refs['registerForm'].validate(valid => {
        if (valid) {
          const params = {
            name: this.registerForm.name,
            gender: this.registerForm.gender,
            account: 'a' + this.$md5(this.registerForm.cellphone),
            password: this.$md5(this.registerForm.password),
            email: this.registerForm.email,
            cellphone: this.registerForm.cellphone,
            tag: this.registerForm.tag,
          }
          const query = {
            ver_code: this.registerForm.checkCode
          }
          this.$loading(this.option)
          this.$api.register({ ...params }, { ...query }).then(res => {
            if (res.status == '$SUCCESS') {
              this.$message.success('注册成功')
              this.$router.push('/home')
              this.$refs.registerForm.resetFields()
            } else if (res.status == 'REGISTER_USER') {
              this.$message.error('当前用户已注册，请更换手机号')
            }
          }).catch(() => {
            this.$message.error(res.message)
          }).finally(() => {

            this.$loading().close()
          })
        }
      })
    },
    goLogin() {
      // 登陆窗口统一由vuex控制
      this.$store.commit('user/SET_LOGIN', true)
      console.log(this.$store.state.user.loginDialog)
    },
    inputCode() {
      this.$refs['registerForm'].validateField('cellphone', valid => {
        if (!valid) {
          this.getRegisterCode()
        }
      })
    },
    getRegisterCode() {
      const params = {
        op: "send_register_ver_code",
        reciever: this.registerForm.cellphone
      }
      this.$api.getRegisterCode({ ...params }).then(res => {
        if (res.status == '$SUCCESS') {
          this.$message.success('获取短信验证码')
          let time = 60
          this.wait = true
          this.codeMessage = time + 's后重新发送'
          this.timer = setInterval(() => {
            time--
            this.codeMessage = time + 's后重新发送'
            if (time <= 0) {
              this.codeMessage = '获取验证码'
              clearInterval(this.timer)
              this.timer = null
              this.wait = false
            }
          }, 1000);
        }
      })
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
  }
}
</script>

<style lang="less">
.register {
  max-width: 1368px;
  margin: 0 auto;
  padding: 60px 0 0;

  .g-title {
    margin-bottom: 40px;
    .left {
      font-size: 30px;
      font-family: Source Han Serif SC;
      font-weight: 800;
      color: #000000;
      line-height: 30px;
    }

    .right {
      float: right;
      font-size: 16px;
      color: #333;

      .go-login {
        color: #AA9884;
        cursor: pointer;
      }
    }
  }
  .g-form {
    max-width: 1368px;
    padding: 37px 500px 60px 210px;
    background: #fff;
  }
  .el-input__inner {
    background-color: #f3f4f4;
    border-radius: 0;
  }

  input::-webkit-input-placeholder {
    color: #999;
  }

  .el-radio__inner:hover {
    border-color: #ccc;
  }

  .el-radio__input.is-checked .el-radio__inner {
    background: #fff;
    border-color: #ccc;
  }

  .el-radio__inner::after {
    background: #333;
  }

  .el-radio__input.is-checked+.el-radio__label {
    color: #333;
  }

  .el-form-item__label {
    width: 100%;
    text-align: left;
  }

  .el-checkbox.is-bordered+.el-checkbox.is-bordered {
    margin-left: 0;
  }

  .my-label .el-checkbox__input {
    display: none;
  }

  .el-checkbox__label {
    padding: 0;
  }

  .el-checkbox.is-bordered.el-checkbox--small {
    width: 132px;
    height: 50px;
    line-height: 35px;
    font-size: 16px;
    text-align: center;
    border-radius: 0;
    margin-right: 18px;
    margin-bottom: 15px;
    color: #999;
  }

  .el-checkbox.is-bordered.is-checked {
    border-color: #E0CBB4;
    background-color: #EEE4D9;
  }

  .el-checkbox__input.is-checked+.el-checkbox__label {
    color: #333;
  }

  .argeement {
    font-size: 16px;
  }

  .mark {
    font-size: 16px;
    color: #AA9884;
    cursor: pointer;
  }

  .line {
    width: 100%;
    height: 1px;
    background: #E8E8E8;
    transform: scaleY(0.8);
    margin: 40px 0;
  }

  .btn {
    width: 220px;
    height: 48px;
    background: #E0CBB4;
    color: #333;
    line-height: 48px;
    text-align: center;
    margin: 0 auto;
    cursor: pointer;
    font-size: 16px;

    &.el-button {
      display: flex;
      align-items: center;
      margin: 0 auto;
      border-radius: 0;
      justify-content: center;
    }
  }

  .disabledBtn {
    pointer-events: none;
  }

  .btnBox-wrap {
    position: absolute;
    right: 0;
    bottom: 18px;
  }

  .el-input--small .el-input__inner {
    height: 50px;
  }
}
</style>